package cn.disicn.util;

import java.io.File;

import org.apache.commons.lang3.StringUtils;

import com.aliyun.oss.OSSClient;
import com.jfinal.kit.PropKit;

import cn.disicn.common.ServerResponse;

public class FileUploadUtil {

	private final static String endpoint = PropKit.use("fileUpload.properties").get("endPoint");
	private final static String accessKeyId = PropKit.use("fileUpload.properties").get("accesskeyID");
	private final static String accessKeySecret = PropKit.use("fileUpload.properties").get("accesskeySecret");
	private final static String bucket = PropKit.use("fileUpload.properties").get("bucket");

	/**
	 * 上传图片
	 * 
	 */
	public static ServerResponse<String> fileUpload(File file, String gon) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			String url = gon + file.getName();
			ossClient.putObject(bucket, url, file);
			url = "http://" + bucket + "." + endpoint + url;
			return ServerResponse.createBySuccess(url);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			// 关闭client
			ossClient.shutdown();
		}
		return ServerResponse.createByError();
	}

	/**
	 * 删除图片
	 */
	public static ServerResponse<String> delFile(String fileName) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			if (!StringUtils.isBlank(fileName)) {
				ossClient.deleteObject(bucket, fileName);
				return ServerResponse.createBySuccess();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			// 关闭client
			ossClient.shutdown();
		}
		return ServerResponse.createByError();
	}

}
